import 'dart:async';
import 'dart:developer' as d;

import 'package:flutter_baselib/adapter/log_adapter.dart';
import 'package:logger/logger.dart';

export 'package:logger/logger.dart';
export 'package:cherrilog/cherrilog.dart';

class LoggerUtil {
  LogAdapter logger;

  LoggerUtil({required this.logger});

  set adapter(LogAdapter logger) {
    this.logger = logger;
  }

  void e(dynamic message,
      {DateTime? time, Object? error, StackTrace? stackTrace}) {
    logger.e(message, error: error, time: time, stackTrace: stackTrace);
  }

  void w(dynamic message,
          {DateTime? time, Object? error, StackTrace? stackTrace}) =>
      logger.w(message, error: error, time: time, stackTrace: stackTrace);

  void i(dynamic message,
          {DateTime? time, Object? error, StackTrace? stackTrace}) =>
      logger.i(message, error: error, time: time, stackTrace: stackTrace);

  void d(dynamic message,
          {DateTime? time, Object? error, StackTrace? stackTrace}) =>
      logger.d(message, error: error, time: time, stackTrace: stackTrace);

  void f(dynamic message,
          {DateTime? time, Object? error, StackTrace? stackTrace}) =>
      logger.f(message, error: error, time: time, stackTrace: stackTrace);
}

// Logger logger = Logger(filter: AppLogFilter(), output: AppLogOutput());

class AppLogFilter extends LogFilter {
  final bool showLog;

  AppLogFilter({required this.showLog});

  @override
  bool shouldLog(LogEvent event) =>
      event.level == Level.error ||
      (showLog && event.level.index >= level!.index);
}

class AppLogOutput extends LogOutput {
  final DateTime? time;
  final int? sequenceNumber;
  final int level;
  final String name;
  final Zone? zone;
  final Object? error;
  final StackTrace? stackTrace;

  AppLogOutput(
      {this.name = '',
      this.time,
      this.sequenceNumber,
      this.zone,
      this.error,
      this.level = 0,
      this.stackTrace});

  @override
  void output(OutputEvent event) {
    event.lines.forEach((e) => d.log(
          e,
          name: name,
          time: time,
          sequenceNumber: sequenceNumber,
          zone: zone,
          error: error,
          level: level,
          stackTrace: stackTrace,
        ));
  }
}
